package com.my.study.utils;

import org.apache.rocketmq.common.message.Message;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 分割消息
 * <p>
 * 当批量发送消息的总内存大于1MB时，会进行分割，使其小于1MB
 *
 * @author: yidujun
 * @create: 2021/07/29 16:44
 */
public class ListSplitter implements Iterator<List<Message>> {
    private final int SIZE_LIMIT = 1000 * 1000;
    private final List<Message> messages;
    private int currIndex;

    public ListSplitter(List<Message> messages) {
        this.messages = messages;
    }

    @Override
    public boolean hasNext() {
        return currIndex < messages.size();
    }

    @Override
    public List<Message> next() {
        int nextIndex = currIndex;
        int totalSize = 0;

        for (; nextIndex < messages.size(); nextIndex++) {
            Message message = messages.get(nextIndex);
            int tempSize = message.getTopic().length() + message.getBody().length;
            Map<String, String> properties = message.getProperties();
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                tempSize += entry.getKey().length() + entry.getValue().length();
            }
            //  for log overhead
            tempSize += 20;

            if (tempSize > SIZE_LIMIT) {
                if (nextIndex - currIndex == 0) {
                    nextIndex++;
                }
                break;
            }

            if (tempSize + totalSize > SIZE_LIMIT) {
                break;
            } else {
                totalSize += tempSize;
            }
        }

        List<Message> subList  = this.messages.subList(currIndex, nextIndex);
        currIndex = nextIndex;

        return subList;
    }
}
